package com.travel.server.manager.impl.command.customer;

import com.travel.common.CommonConstant;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dto.request.customer.DeleteCustomerTagRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.CustomerTagDal;
import com.travel.server.manager.impl.dal.CustomerTagDal.CustomerTagParam;
import com.travel.server.manager.model.CustomerTagInfo;
import com.travel.server.manager.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018\11\11 0011 20:09
 * @Desc:
 */
@Component
@Slf4j
public class DeleteCustomerTagCommand extends AbstractCommand<DeleteCustomerTagRequest, EmptyResponse> {

    @Autowired
    private CustomerTagDal customerTagDal;

    @Override
    protected void checkInput(DeleteCustomerTagRequest request) {
        if(request.getId() == null || request.getTagId() == null){
            throwInvalidParam();
        }
    }

    @Override
    public EmptyResponse handle(DeleteCustomerTagRequest request) {
        UserInfo userInfo = getUserInfo();
        Date now = new Date();

        CustomerTagParam param = new CustomerTagParam();
        param.setTagIdList(Arrays.asList(request.getTagId()));
        param.setCustomerId(request.getId());
        List<CustomerTagInfo> list = customerTagDal.selectByExample(param);

        CustomerTagInfo customerTagInfo = CollectionUtil.getFirst(list);
        if(customerTagInfo == null){
            log.error("未查询到客户标签绑定关系, tagId {}, customerId {}", request.getTagId(), request.getId());
            throw new WorkException(WorkCode.RECORD_NOT_EXIST);
        }

        customerTagInfo.setState(CommonConstant.NO);
        customerTagInfo.setUpdateTime(now);
        customerTagInfo.setUpdateBy(userInfo.getName());
        customerTagDal.insertOrUpdate(customerTagInfo);

        return new EmptyResponse();
    }
}
